package com.eecs393.drymouth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ConditionResults extends ListActivity implements OnItemClickListener {
	private JSONObject[] myJSONs = new JSONObject[10];
	private int myJSONs_Size = 0;
	private final int NUM_RESULTS = 10;
	private String[] myConditions;
	private ListView lv;
	private String rawData;
	private String[] ids;
	private String[] myDescription;
	private ArrayList<JSONObject> myLinks;
	private boolean loggedIn = false;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Bundle extras = this.getIntent().getExtras();
		String symptoms = extras.getString("symptomkey");
		loggedIn = extras.getBoolean("loginstatuskey");
		
		String url = "http://veysel.case.edu/drymouth/suggest/json/" + symptoms + "/" + NUM_RESULTS;
		
		connect(url);
		
		parseJSONs(rawData);
		
		fillConditions();			
        
        setListAdapter(new ArrayAdapter<String>(this, R.layout.main2, myConditions));

        lv = getListView();
        lv.setTextFilterEnabled(true);

        lv.setOnItemClickListener(this); /*new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,
              int position, long id) {
            // When clicked, show a toast with the TextView text
//            Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
//            Toast.LENGTH_SHORT).show();
                
              if (position == 0 || position == NUM_RESULTS-1){
            	  Intent newSearch = new Intent(ConditionResults.java, ConditionSearch.class);
            	  startActivity(newSearch);
              }
          }
        });
        */
    }
    
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id){
    	if (position == 0 || position == myJSONs_Size+2){
      	  Intent newSearch = new Intent(this, ConditionSearch.class);
      	  newSearch.putExtra("login_status",loggedIn);
      	  if (loggedIn)	
      	  	newSearch.putExtra("newLoginKey",!loggedIn);
      	  startActivity(newSearch);
        }
    	else{
    		connect("http://veysel.case.edu/drymouth/conditions/json/" + ids[position-2]);
    		
    		parseDescription(rawData);
    		
    		AlertDialog.Builder adb = new AlertDialog.Builder(this);
    		adb.setTitle("Additional Information");    		
    		
    		String condition = myDescription[0];
    		
    		String info = "Condition: " + condition + "\n\n";
    		info += "Symptoms:\n";
    		
    		for (int i = 1; i < myDescription.length; i++){
    			info += "-" + myDescription[i] + "\n";
    		}
    		
    		condition = condition.replace(' ','+');
    		
    		if (loggedIn){
    			myLinks = new ArrayList<JSONObject>();
    			connect("http://www.smigula.com/drymouth/conditions/pubmed_json/" + condition);
    			parseLinks(rawData);
    			
    			info += "\n";
    			
    			for (int i = 0; i < myLinks.size(); i++){
    				try{
    					JSONObject json = myLinks.get(i);
    					info += "-" + json.getString("title") + "\n";
    					info += "(" + json.getString("source") + ", " + json.getString("pubinfo") + ")\n\n";
    				}
    				catch (JSONException e){
    					e.printStackTrace();
    				}
    			}
    		}
    		
    		adb.setMessage(info);
    		adb.setCancelable(true);
    		adb.setNeutralButton("Close", new DialogInterface.OnClickListener(){
    			@Override
    			public void onClick(DialogInterface dialog, int which){
    				dialog.dismiss();
    			}
    		});
    		AlertDialog ad = adb.create();
    		ad.show();
    	}
    }
    
    protected void connect(String url)
    {
 
        HttpClient httpclient = new DefaultHttpClient();
 
        // Prepare a request object
        HttpGet httpget = new HttpGet(url); 
 
        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);      
 
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release
 
            if (entity != null) {
 
                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                rawData = convertStreamToString(instream);
//                Log.i("Praeda",result);
          
             // Closing the input stream will trigger connection release
            	instream.close();
            }
        } 
        catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
    
    protected void parseJSONs(String s){
    	if (s.charAt(0) == '[');
    		String working = s.substring(1);
        
        for (int i = 0; working.charAt(0) != ']' && i < NUM_RESULTS; i++){
        	
        	int start = working.indexOf('{');
        	int end = working.indexOf('}')+1;
        	String jString = working.substring(start,end);
        	
        	try{
        		JSONObject json = new JSONObject(jString);        		        	
        		myJSONs[i] = json;
        		myJSONs_Size++;
        	}
        	catch (JSONException e) {                
                e.printStackTrace();
            }
        	
        	working = working.substring(end);
        }
    }
    
    protected void parseLinks(String s){
    	if (s.charAt(0) == '[');
		String working = s.substring(1);
    
		for (int i = 0; working.charAt(0) != ']'; i++){
    	
			int start = working.indexOf('{');
			int end = working.indexOf('}')+1;
			String jString = working.substring(start,end);
			
			try{
				JSONObject json = new JSONObject(jString);        		        	
				myLinks.add(json);
			}
			catch (JSONException e) {                
				e.printStackTrace();
			}
    	
			working = working.substring(end);
		}
    }
    
    protected void parseDescription(String s){    	
    	String working = s.substring(s.indexOf(':')+1);
    	
    	int start = working.indexOf('{');
    	int end = working.indexOf('}')+1;
    	String jString = working.substring(start,end);
    	
    	int numSymptoms = 0;
    	JSONObject json;
    	String cName = new String();
    	
    	try{
    		json = new JSONObject(jString);
    		cName = json.getString("c_name");
    		numSymptoms = Integer.parseInt(json.getString("s_count"));
    	}
    	catch (JSONException e){
    		e.printStackTrace();
    	}
    	
    	myDescription = new String[numSymptoms+1];
    	myDescription[0] = cName;
    	
    	working = working.substring(end);
    	
    	working = working.substring(working.indexOf('[')+1);
    	
    	for (int i = 0; i < numSymptoms; i++){
    		start = working.indexOf('{');
    		end = working.indexOf('}')+1;
    		jString = working.substring(start,end);
    		try{
    			json = new JSONObject(jString);
    			myDescription[i+1] = json.getString("s_name");
    		}
    		catch (JSONException e){
    			e.printStackTrace();
    		}
    		
    		working = working.substring(end);
    	}
    }
    
    protected String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
    
    protected void fillConditions(){
    	myConditions = new String[myJSONs_Size+3];
    	ids = new String[myJSONs_Size];
    	
    	myConditions[0] = "CLICK HERE TO BEGIN A NEW SEARCH";
		myConditions[myConditions.length-1] = "CLICK HERE TO BEGIN A NEW SEARCH";
		
		if (myConditions.length > 3){
			
			myConditions[1] = "Condition Suggestions:";

			for (int i = 2; i < myConditions.length-1; i++){
//				myConditions[i] = myJSONs[i].toString();
				try {
					JSONObject jo = myJSONs[i-2];
					ids[i-2] = jo.getString("c_id");
					myConditions[i] = "Rank: " + (i-1) + "\nCondition: " + jo.getString("c_name") + "\nScore: " + jo.getString("score");
				}
				catch (JSONException e){
				e.printStackTrace();
				}
			}
		}
		else myConditions[1] = "Your search did not yield any results.";
    }
    
    protected String getCondition(int index){
    	if (index < 0 || index >= myConditions.length)
    		throw new ArrayIndexOutOfBoundsException();
    	return myConditions[index];
    }
    
    protected JSONObject getJSON(int index){
    	return myJSONs[index];
    }
    
    protected void setJSONs(JSONObject[] jObjs){
    	myJSONs = jObjs;
    	myJSONs_Size = myJSONs.length;
    }
    
    protected String getRawData(){
    	return rawData;
    }
}